;(function(global){
  const fetchReq = function(...args) {
    return new Promise((resolve, reject) => {
      return fetch.call(null, ...args)
        .then(res => res.json())
        .then(json => {
          if (json.status !== 0) {
            reject(new Error('fetch data error'));
          }
          resolve(json);
        })
    })
  }
  const api = {
    /** 获取文件状态 */
    getState() {
      return fetchReq('/files');
    },
    deleteItem(filename) {
      return fetchReq(`/delete/${filename}`, {
        method: 'DELETE',
      });
    },
    /**
     * 解压文件
     * @param {string} filename 文件名
     */
    extractFile(filename) {
      return fetchReq(`/extract/${filename}`)
    },
    /**
     * 为指定文件启动静态服务器
     * @param {string} filename 
     */
    start(filename) {
      return fetchReq(`/start/${filename}`);
    },
    /**
     * 关闭指定的静态服务器
     * @param {string} file 
     */
    close(filename) {
      return fetch(`/close/${filename}`, {
        method: 'DELETE'
      })
    },
    getFileInfo(file) {
      if (!file) {
        return null;
      }
      const fileInfo = {
        size: '',
        name: '',
        file,
      };
      var fileSize = 0;
      if (file.size > 1024 * 1024) {
        fileInfo.size = (file.size / (1024 * 1024)).toFixed(2) + ' MB';
      } else {
        fileInfo.size = (file.size / 1024).toFixed(2) + ' KB';
      }
      fileInfo.name = file.name;
      fileInfo.type = file.type;
      
      return fileInfo;
    },
    updateFile(fileInfo, uploadProgress) {
      return new Promise((resolve, reject) => {
        // setup file info
        if (!fileInfo) {
          return null;
        }

        var fd = new FormData();
        fd.append("zipfile", fileInfo.file);
        var xhr = new XMLHttpRequest();
        xhr.upload.addEventListener("progress", uploadProgress, false);
        xhr.addEventListener('load', () => {
          resolve();
        }, false);
        xhr.addEventListener('error', () => {
          reject(new Error('error'));
        }, false);
        xhr.addEventListener('abort', () => {
          reject('abort');
        }, false);
        xhr.open("POST", "/upload");
        xhr.send(fd);
      })
    }
  }

  global['pmTools'] = {
    api,
  }
})(window);
